package com.tools.web.http;

import com.tools.common.object.Note;

import java.util.Locale;

/**
 * HTTP 请求方式 method 的枚举类
 * */
@Note("HTTP 请求方式 method 的枚举类")
public enum HttpMethodEnum {

    GET(0, "GET"),
    POST(1, "POST"),
    PUT(2, "PUT"),
    DELETE(3, "DELETE");

    HttpMethodEnum(int code, String name) {
        this.code = code;
        this.name = name;
    }

    private final String name;

    private final int code;

    public int getCode() {
        return code;
    }

    public String getName() {
        return name;
    }

    public boolean eq(String name) {
        return this.name.equals(name);
    }

    public boolean eqIgnoreCase(String name) {
        return this.name.equalsIgnoreCase(name);
    }

    @Override
    public String toString() {
        return this.name();
    }

    /* **************************************************************************************
     *
     *          获取枚举实例
     *
     * **************************************************************************************
     * */


    @Note("安全地根据编码获取对应的实例，获取不到不会抛异常")
    public static HttpMethodEnum getEnumSafe(int code) {
        switch (code) {
            case 0 : return GET;
            case 1 : return POST;
            case 2 : return PUT;
            case 3 : return DELETE;
            default: return null;
        }
    }


    @Note("根据编码获取对应的实例，获取不到会抛异常")
    public static HttpMethodEnum getEnum(int code) {
        HttpMethodEnum instance = getEnumSafe(code);
        if(instance == null) throw new IllegalArgumentException("没有找到 【" + code + "】 对应的枚举实例");
        return instance;
    }


    @Note("安全地根据名称获取对应的实例（对比过程忽略字符串大小写），获取不到不会抛异常")
    public static HttpMethodEnum getEnumSafe(String name) {
        switch (name.toUpperCase(Locale.ROOT)) {
            case "GET": return GET;
            case "POST": return POST;
            case "PUT": return PUT;
            case "DELETE": return DELETE;
            default: return null;
        }
    }


    @Note("根据名称获取对应的实例（对比过程忽略字符串大小写），获取不到会抛异常")
    public static HttpMethodEnum getEnum(String name) {
        HttpMethodEnum instance = getEnumSafe(name);
        if(instance == null) throw new IllegalArgumentException("没有找到 【" + name + "】 的枚举实例");
        return instance;
    }
}
